<template>
  <div class="container">
    <div class="nav" style="margin-bottom: 10px">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="待审核" name="0"></el-tab-pane>
        <el-tab-pane label="驳回" name="1"></el-tab-pane>
        <el-tab-pane label="已完成" name="3"></el-tab-pane>
      </el-tabs>
    </div>
    <el-collapse-transition>
      <div class="query" v-show="isShowForm">
        <div class="header">
          <span style="color: #333333">数据查询</span>
          <p
            @click="isShowForm = false"
            style="font-size: 14px; color: #409eff; cursor: pointer"
          >
            收起
          </p>
        </div>
        <el-form
          label-width="70px"
          :inline="true"
          ref="form"
          :model="queryForm"
          size="mini"
        >
          <el-form-item label="订单信息">
            <el-input
              placeholder="请输入调整编号/商品信息"
              v-model="queryForm.info"
            ></el-input>
          </el-form-item>
          <el-form-item class="formItem" label="申请人">
            <el-select
              v-model="queryForm.applicant"
              filterable
              placeholder="请输入申请人"
              clearable
            >
              <el-option
                v-for="items in applicant"
                :key="items.label"
                :label="items.value"
                :value="items.label"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="仓库">
            <el-select
              v-model="queryForm.wareName"
              filterable
              placeholder="请选择仓库名称"
              clearable
              default-first-option
            >
              <el-option
                v-for="items in wareData"
                :key="items.id"
                :label="items.name"
                :value="items.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="流程节点" v-if="activeName == 0">
            <el-select
              v-model="queryForm.process"
              filterable
              placeholder="选择流程节点"
              clearable
            >
              <el-option
                v-for="items in nodes"
                :key="items.dictName"
                :label="items.dictName"
                :value="items.dictName"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="申请时间">
            <div class="selectDate">
              <el-date-picker
                v-model="queryForm.date"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              size="mini"
              @click="searchEvent"
              v-on:keyup.enter="searchEvent"
            >
              搜索
            </el-button>
            <el-button size="mini" @click="reset"> 重置 </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-collapse-transition>

    <div class="btns" v-if="activeName != 3">
      <el-button
        type="primary"
        size="mini"
        @click="approval('', '', 1, 1)"
        v-if="parArray.indexOf('tzApproveCode') != -1"
        >批量批准</el-button
      >
      <el-button
        type="primary"
        size="mini"
        @click="approval('', '', 1, 1)"
        v-if="parArray.indexOf('tzMoreBack') != -1 && activeName != 1"
        >批量驳回</el-button
      >
      <el-button
        size="small"
        type="primary"
        @click="batchGuideOrder"
        v-if="parArray.indexOf('tzMoreGuide') != -1 && activeName != 1"
        >批量导单</el-button
      >
      <el-button
        type="primary"
        size="mini"
        @click="isShowForm = true"
        v-show="!isShowForm"
        style="position: absolute; right: 10px"
        >搜索展开</el-button
      >
    </div>

    <div class="tableContext">
      <el-table
        ref="table"
        :data="table.list"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @row-click="rowEvent"
      >
        <el-table-column type="selection" width="50"> </el-table-column>
        <el-table-column label="序号" type="index" width="50"></el-table-column>
        <el-table-column label="调整编号" min-width="150">
          <template slot-scope="scope">
            <p @click="openDetail(scope.row)">{{ scope.row.oddNumbers }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="progressBar" label="进度" min-width="180">
          <template slot-scope="scope">
            <p @click="openDetail(scope.row)">{{ scope.row.progressBar }}</p>
          </template>
        </el-table-column>
        <el-table-column label="申请人">
          <template slot-scope="scope">
            <p @click="openDetail(scope.row)">{{ scope.row.proposerName }}</p>
          </template>
        </el-table-column>
        <el-table-column label="物流审核">
          <template slot-scope="scope">
            <p
              @click="openDetail(scope.row)"
              v-if="scope.row.auditor['物流经理审批']"
            >
              {{ scope.row.auditor["物流经理审批"] }}
            </p>
            <p @click="openDetail(scope.row)" v-else>--</p>
          </template>
        </el-table-column>
        <el-table-column label="财务审核">
          <template slot-scope="scope">
            <p
              @click="openDetail(scope.row)"
              v-if="scope.row.auditor['财务经理审批']"
            >
              {{ scope.row.auditor["财务经理审批"] }}
            </p>
            <p @click="openDetail(scope.row)" v-else>--</p>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="date" label="驳回时间"> </el-table-column> -->
        <el-table-column
          prop="date"
          label="申请时间"
          min-width="110"
          v-if="activeName != '1'"
        >
          <template slot-scope="scope">
            <p @click="openDetail(scope.row)">
              {{ $moment(scope.row.createTime) }}
            </p>
          </template>
        </el-table-column>

        <el-table-column
          prop="date"
          label="驳回时间"
          min-width="110"
          v-if="activeName == '1'"
        >
          <template slot-scope="scope">
            <p @click="openDetail(scope.row)">
              {{ $moment(scope.row.createTime) }}
            </p>
          </template>
        </el-table-column>
        <!-- <el-table-column
          prop="date"
          label="驳回原因"
          min-width="110"
          v-if="activeName == '1'"
          >--</el-table-column
        > -->

        <el-table-column label="操作" width="160">
          <template slot-scope="scope">
            <div class="operation">
              <span
                v-if="
                  activeName == '1' &&
                  scope.row.isSelf == '1' &&
                  parArray.indexOf('tzAgainCode') != -1
                "
                @click="wareFix(scope.row)"
                >修改</span
              >
              <span
                v-if="
                  activeName == '0' &&
                  scope.row.isApprove == '1' &&
                  parArray.indexOf('TzaloneApproveCode') != -1
                "
                @click="
                  approval(scope.row.oddNumbers, scope.row.procInstId, 1, 2)
                "
                >批准</span
              >
              <span
                style="color: #ff5656"
                v-if="
                  activeName == '0' &&
                  scope.row.isApprove == '1' &&
                  parArray.indexOf('tzAloneBackCode') != -1
                "
                @click="rejectEvent(scope.row)"
                >驳回</span
              >
              <span
                v-if="parArray.indexOf('tzlc') != -1"
                @click="polliingEvent(scope.row)"
                >流程</span
              >
              <span
                v-if="
                  (activeName == '1' || activeName == '0') &&
                  scope.row.isSelf == '1' &&
                  parArray.indexOf('tzDelectCode') != -1
                "
                class="delect"
                @click="delectEvent(scope.row, scope.$index)"
                >删除</span
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="height: 20px"></div>
    <!-- 分页start -->
    <div class="page" v-if="table.totalNum > 0">
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNo"
          :page-sizes="[10, 20, 50, 100, 200]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="table.totalNum"
          prev-text="上一页"
          next-text="下一页"
        >
        </el-pagination>
      </div>
    </div>
    <!-- 分页end -->

    <el-drawer
      title=""
      :visible.sync="drawer"
      :with-header="false"
      :append-to-body="true"
      size="40%"
    >
      <div class="drawerBox">
        <p class="header">库存调整单详情</p>
        <div class="nav">
          <p>调整编号：{{ detail.oddNumbers }}</p>
          <p>
            <span>申请时间：{{ $moment(detail.createdTime) }}</span>
            <span>申请人：{{ detail.proposerName }}</span>
          </p>
        </div>
        <el-table :data="detail.goods" :stripe="true">
          <el-table-column
            label="序号"
            type="index"
            width="50"
          ></el-table-column>
          <el-table-column
            prop="goodsName"
            label="商品信息"
            width="220"
          ></el-table-column>
          <el-table-column
            prop="frontPracticalStock"
            label="原来库存"
            width="120"
          ></el-table-column>
          <el-table-column
            prop="laterPracticalStock"
            label="修改库存"
            width="120"
          ></el-table-column>
          <el-table-column label="修改数量" width="120">
            <template slot-scope="scope">
              <el-popover
                placement="left-start"
                title=""
                width="200"
                trigger="hover"
                content="这是一段内容,这是一段内容,这是一段内容,这是一段内容。"
              >
              <div>
                <div style="width: 100%;
    display: flex;
    justify-content: space-between;" v-for="item in scope.row.wars">
                  <span>
                    {{item.warName}}
                  </span>
                  <span>
                    {{item.frontQuantity}}
                  </span>
                  <span>
                    {{item.difference}}
                  </span>
                </div>
              </div>
                <div slot="reference">
                  <p v-if="scope.row.addFixNumber < 0">
                    {{ scope.row.addFixNumber }}
                  </p>
                  <p v-else>+{{ scope.row.addFixNumber }}</p>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column
            prop="warAdName"
            label="调整原因"
            show-overflow
            min-width="120"
          ></el-table-column>
        </el-table>
      </div>
    </el-drawer>

    <!-- 驳回操作 -->
    <el-dialog :visible.sync="reject" :append-to-body="true" title="审批意见">
      <div class="content">
        <!-- <span style="display: inline-block; line-height: 30px">审批意见:</span> -->
        <el-input
          type="textarea"
          placeholder="请输入驳回内容"
          v-model="textarea"
        ></el-input>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button
          size="mini"
          type="primary"
          @click="
            reject = false;
            approval(row.oddNumbers, row.procInstId, 2, 2);
          "
          >驳回
        </el-button>
        <el-button size="mini" @click="reject = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 对话弹框 -->
    <el-dialog
      :visible.sync="dialogFormVisible"
      :append-to-body="true"
      title="审核过程"
    >
      <el-table :data="polliing" style="width: 100%">
        <el-table-column type="index" label="步骤" width="50"></el-table-column>
        <el-table-column
          label="任务节点"
          prop="taskName"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="办理人"
          prop="assignee"
          width="110"
        ></el-table-column>
        <el-table-column
          label="审批开始时间"
          prop="startTime"
        ></el-table-column>
        <el-table-column label="审批结束时间">
          <template slot-scope="props">
            <span v-if="props.row.endTime">{{ props.row.endTime }}</span>
            <span v-else>正在处理中...</span>
          </template>
        </el-table-column>
        <el-table-column label="审批意见" :show-overflow-tooltip="true">
          <template slot-scope="props">
            <span v-if="props.row.comment">{{ props.row.comment }}</span>
            <span v-if="props.row.comment">/</span>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 对话弹框 -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      isShowForm: true,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      activeName: "0",
      queryForm: {
        applicant: "",
        wareName: "",
        date: [],
        info: "",
        process: "",
      },
      multipleSelection: [],
      wareData: [],
      client: [],
      table: [],
      pageSize: 10,
      pageNo: 1,
      applicant: [],
      drawer: false,
      detail: "",
      reject: false,
      textarea: "",
      row: "",
      dialogFormVisible: false,
      polliing: [],
      nodes: [],
      limits: "",
      parArray: [],
    };
  },
  created() {
    // 权限设定判断
    this.limits = JSON.parse(sessionStorage.getItem("limit"));
    const params = this.limits.buttonTreeDto.filter(
      (item) => item.menuCode === "wareUpdateListCode"
    );
    params[0].buttonList.forEach((item) => {
      this.parArray.push(item.code);
    });
    // 权限设定判断
    this.wareList(); //仓库列表
    this.applicantlist(); //申请人列表
    this.axiosList();
    this.processNode(); //节点下拉框

    let _this = this;
    document.onkeydown = function (e) {
      let key = window.event.keyCode;
      if (key == 13) {
        _this.searchEvent();
      }
    };
  },
  beforeRouteLeave(to, form, next) {
    document.onkeydown = null;
    next();
  },
  activated() {
    this.axiosList();
  },
  methods: {
    batchGuideOrder() {
      if (!this.multipleSelection.length) {
        this.$message.warning("没选择");
        return;
      }
      this.download(
        "/order/stockControl/adjustExportExcel",
        this.multipleSelection.map((res) => res.oddNumbers)
      );
    },
    // 流程节点下拉框
    processNode() {
      this.axios
        .post("/order/stockControl/node", {
          headers: {
            isLoading: false,
          },
        })
        .then((res) => {
          // console.log(res);
          this.nodes = res.data;
        });
    },
    rejectEvent(row) {
      this.reject = true;
      this.row = row;
      this.textarea = "";
    },
    //   批准
    approval(orderIds, proInsIds, status, ifpl) {
      // ifpl  判断是批量操作（1）&单个操作（2）
      let orderIdsParam = [];
      let proInsIdsParam = [];
      if (ifpl == 1) {
        for (let i in this.multipleSelection) {
          orderIdsParam.push(this.multipleSelection[i].oddNumbers);
          proInsIdsParam.push(this.multipleSelection[i].procInstId);
        }
      } else {
        orderIdsParam.push(orderIds);
        proInsIdsParam.push(proInsIds);
      }
      
      if(orderIdsParam.length==0){
         this.$message.warning("未选择审批的调整单")
         return false;
      }

      this.axios
        .post("order/stockControl/commitTask", {
          comment: this.textarea,
          orderIds: orderIdsParam,
          proInsIds: proInsIdsParam,
          result: status, //1批准 2驳回
          type: 2,
        })
        .then((res) => {
          //   console.log(res);
          if (res.code == 0) {
            this.$message.success("操作成功");
            this.textarea = "";
            this.axiosList();
          } else {
            this.$message.error(res.message);
          }
        });
    },
    // 修改
    wareFix(row) {
      // console.log(row)
      this.axios
        .get("/order/stockControl/allotDetails?oddNumber=" + row.oddNumbers)
        .then((res) => {
          // console.log(res)
          this.$router.push({
            name: "addAdjustment",
            query: {
              obj: JSON.stringify({
                gids: res.data.goods.map((res) => Number(res.goodsId)),
                gType: res.data.goods[0].gtype,
                type: "TT",
                isNewO: row.oddNumbers,
              }),
              isCk:true
            },
          });
        });
    },
    rowEvent(row) {
      this.$refs.table.toggleRowSelection(row);
    },
    openDetail(row) {
      this.drawer = true;
      this.detail = "";
      this.axios
        .get("/order/stockControl/allotDetails?oddNumber=" + row.oddNumbers, {
          headers: {
            isLoading: false,
          },
        })
        .then((res) => {
          //   console.log(res);
          if (res.code == 0) {
            let fixNum = 0;
            for (let i in res.data.goods) {
              res.data.goods[i].addFixNumber = 0;
              for (let j in res.data.goods[i].wars) {
                res.data.goods[i].addFixNumber += Number(
                  JSON.parse(res.data.goods[i].wars[j].difference)
                );
              }
            }

            this.detail = res.data;
          } else {
            this.$message.error(res.message);
          }
        });
    },
    //   列表数据请求
    axiosList() {
      let beginTime = "";
      let endTime = "";

      if (this.queryForm.date.length) {
        beginTime = this.queryForm.date[0] + " 00:00:00";
        endTime = this.queryForm.date[1] + " 23:59:59";
      }
      this.axios
        .post(
          "/order/stockControl/allotList",
          {
            endTime: endTime,
            flow: this.activeName,
            keyWord: this.queryForm.info,
            pageNo: this.pageNo,
            pageSize: this.pageSize,
            proposerName: this.queryForm.applicant,
            startTime: beginTime,
            type: 2,
            warId: this.queryForm.wareName,
            node: this.queryForm.process,
          },
          {
            headers: {
              isLoading: true,
            },
          }
        )
        .then((res) => {
          if (res.code == 0) {
            this.table = res.data;
          } else {
            this.$message.error(res.message);
          }
        });
    },
    // 重置
    reset() {
      this.queryForm = {
        applicant: "",
        wareName: "",
        date: "",
        info: "",
      };
      this.pageSize = 10;
      this.pageNo = 1;
      this.axiosList();
    },
    searchEvent() {
      this.pageSize = 10;
      this.pageNo = 1;
      this.axiosList();
    },
    // 删除
    delectEvent: _.debounce(function (row, index) {
      this.$confirm("确定删除该调整单数据?, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let url = "";
          if(this.activeName == "1"){
            url = "/order/stockControl/close?oddNumber=" + row.oddNumbers+"&type=1";
          }else{
            url = "/order/stockControl/close?oddNumber=" + row.oddNumbers;
          }
          this.axios
            .get(url)
            .then((res) => {
              //   console.log(res);
              if (res.code == 0) {
                this.$message.success("删除成功!");
                this.table.list.splice(index, 1);
              } else {
                this.$message.error(res.message);
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    }, 300),

    wareList() {
      this.axios
        .post("/order/comm/commWarehouse/list",{
        pageSize:999,
        pageNo:1
      }, {
          headers: { isLoading: false },
        })
        .then((res) => {
          if (res.code == 0) {
            this.wareData = res.data.list;
          } else {
            this.$message.error(res.message);
          }
        });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      //   console.log(this.multipleSelection);
    },
    handleClick(val) {
      this.table = [];
      this.pageNo = 1;
      this.pageSize = 10;
      this.axiosList();
    },
    //  申请人
    applicantlist() {
      this.axios
        .post("/order/stockControl/applicantList", {
          headers: {
            isLoading: false,
          },
        })
        .then((res) => {
          console.log(res);
          if (res.code == 0) {
            this.applicant = res.data;
          } else {
            this.$message.error(res.message);
          }
        });
    },

    //** 查询流程 **//
    polliingEvent(row) {
      this.polliing = [];
      this.dialogFormVisible = true;
      //待发货流程信息
      this.axios
        .get("/order/order/user/selectHiTask?taskId=" + row.procInstId, {
          headers: {
            isLoading: false,
          },
        })
        .then((res) => {
          if (res.code == 0) {
            this.polliing = res.data;
          } else {
            this.$message.error(res.message);
          }
        });
    },

    // 分页
    handleCurrentChange(val) {
      this.pageNo = val;
      this.axiosList();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.axiosList();
    },
  },
};
</script>

<style scoped lang="scss">
/deep/.el-form-item--mini.el-form-item,
.el-form-item--small.el-form-item {
  margin-bottom: 0px;
}
.btns {
  margin-bottom: 10px;
}

/deep/.el-table .cell {
  text-align: center !important;
}
.drawerBox {
  padding: 10px;
  .nav {
    width: 100%;
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    span {
      display: inline-block;
      margin-left: 10px;
    }
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
  }
  /deep/.el-table tr:nth-child(2n) {
    background: #4168e7;
  }
}
.selectDate {
  display: inline-block;
  margin-right: 20px;

  span {
    display: inline-block;
    font-size: 15px;
    margin-right: 15px;
    vertical-align: middle;
  }

  .picker {
    display: inline-block;
    vertical-align: middle;
  }

  /deep/.el-input__inner {
    width: 250px;
    height: 28px;
    line-height: 28px;
  }

  /deep/ .el-date-editor .el-range__icon {
    line-height: 23px;
  }

  /deep/ .el-date-editor .el-range-separator {
    line-height: 23px;
  }

  /deep/.el-date-editor .el-range__close-icon {
    line-height: 22px;
  }
}
.tableContext {
  margin-bottom: 40px;
}
.operation {
  color: #4168e7;
  span {
    cursor: pointer;
    display: inline-block;
    padding: 0 5px;
  }
}

.nav {
  /deep/.el-tabs__item {
    width: 70px;
    text-align: center;
    padding: 0;
  }
}

.query {
  background: #fff;
  padding: 10px;
  margin: 10px 0;
  border-radius: 0px 0px 10px 10px;
  /deep/ .el-form-item label:after {
    content: "";
    display: inline-block;
    width: 100%;
  }
  /deep/ .el-form-item__label {
    text-align: justify;
    height: 40px;
  }
  /deep/.el-input__inner {
    width: 250px;
  }
}

.header {
  padding-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  span {
    font-size: 15px;
    color: #000;
  }

  p {
    color: #4168e7;
    font-size: 12px;
  }
}

/deep/.el-tabs__header {
  margin: 0;
  background: #fff;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
}
/deep/.el-table thead {
  color: #333;
}
.delect {
  color: #ff5656;
}
.page {
  text-align: right;
  width: 100%;
  background: #f5f5f5;
  padding-right: 20px;
  position: fixed;
  bottom: 0px;
  right: 0px;
  z-index: 5;

  span {
    font-size: 14px;
    color: #666;
    display: inline-block;
    margin-left: 10px;
  }

  .el-pagination {
    display: inline-block;
    vertical-align: middle;
  }
}
</style>
